package cn.yy.cloudpay.scan;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.usb.UsbDevice;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.Vibrator;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TwoLineListItem;

import com.android.usbport.ModbusTransfer;
import com.android.usbport.USBManager;
import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.newland.mtype.ModuleType;
import com.newland.mtype.common.MESeriesConst;
import com.newland.mtype.event.DeviceEvent;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.cardreader.CardReader;
import com.newland.mtype.module.common.cardreader.OpenCardReaderEvent;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.light.LightType;
import com.newland.mtype.module.common.rfcard.RFCardType;
import com.newland.mtype.module.common.scanner.BarcodeScanner;
import com.newland.mtype.module.common.scanner.ScannerListener;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.yy.cloudpay.R;
import cn.yy.cloudpay.activity.BaseActivity;
import cn.yy.cloudpay.activity.PayActivity;
import cn.yy.cloudpay.application.CloudPayApplication;
import cn.yy.cloudpay.listener.ITitlebarClickListener;
import cn.yy.cloudpay.ui.ClearEditText;
import cn.yy.cloudpay.util.Constant;
import cn.yy.cloudpay.util.CountDownTimer;
import cn.yy.cloudpay.util.MyUtils;
import cn.yy.cloudpay.util.ObjectGenerator;
import cn.yy.cloudpay.util.SerialUtils;
import cn.yy.cloudpay.util.StringUtil;
import cn.yy.cloudpay.util.WebserviceRequset;
import cn.yy.cloudpay.view.LoadingDialog;
import cn.yy.cloudpay.view.TitlebarLayout;
import cn.yy.cloudpay.view.ToastUtil;

/**
 * 二维码扫描Activity
 * @author yy-01
 *
 */
public class FeixiScanActivity extends BaseActivity {
	public Logger log= Logger.getLogger(this.getClass());

	private TitlebarLayout titlebar;
	private RelativeLayout relativeLayout;
	private Context mContext;
	private Activity activity;
	// 显示支付金额+
	private TextView mTvAmount;
	private TextView mTvDownTimer;
	private ImageView mIvPic;
	private BarcodeScanner scanner;
	private CloudPayApplication mApplication;
	public LoadingDialog mProgress;
	private static Integer SCAN_TIME = 1; // 扫描器运行时长（秒）
	private MyCountDownTimer mc;
	private IndicatorLight light;

	private PopupWindow popupWindow;
	private ArrayAdapter<UsbSerialPort> mAdapter;
	private List<UsbSerialPort> mEntries = new ArrayList<UsbSerialPort>();

	private CardReader cardReader;
	private boolean isPress = false;
	private String paycode="";
	private int equiment=0;	//1:待机，2:运行中
	private TextView statesStr;
	private String redAddr = "0004";
	private View view;
	private boolean initFocus = true;
	private boolean isPay = true;
	private boolean isRestart = true;
	private int ix=5;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scancode);
		mContext = this;
		activity = this;
		mApplication = (CloudPayApplication) getApplication();
		initView();
	}
	
	private void initView() {
		mTvAmount = (TextView) findViewById(R.id.tv_activity_scancode_amuont);
		mTvDownTimer = (TextView) findViewById(R.id.tv_activity_scancode_downtime);
		mIvPic = (ImageView) findViewById(R.id.iv_activity_scancode_pic);
		relativeLayout = (RelativeLayout) findViewById(R.id.titlebar_activity_scancode);
		statesStr = (TextView)findViewById(R.id.tv_status);

		mProgress = new LoadingDialog(mContext, "正在支付，请稍后");
		mTvAmount.setText("欢迎使用飞洗无人洗车");
		mIvPic.setImageResource(R.drawable.feixi);
		mIvPic.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				openDeviceList();
			}
		});

		if("1".equals(mApplication.isMT())) {
			light = (IndicatorLight) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
		}

		titlebar = new TitlebarLayout(mContext, relativeLayout, "请使用二维码付款");
		titlebar.setTitlebarClickListener(new ITitlebarClickListener() {
			@Override
			public void OnRetrunListener(View view) {
				finish();
			}
		});
		long totalTime = SCAN_TIME*24*60*60*1000;
		long day = 1000;
		mc = new MyCountDownTimer(totalTime, day);
	    mc.start();
	}

	/*
	 * 初始化扫描器
	 */
	private void initModule() {
		scanner = mApplication.getScanner();
		scanner.initScanner(this);
	}

	/*
	 * 运行扫描器
	 */
	private void runScanner() {
		light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
		scanner.startScan(SCAN_TIME, TimeUnit.DAYS, new ScannerListener() {
			@Override
			// 异步
			public void onResponse(String[] result) {
				String str = result[0];
				paycode = str;
				stopScanner();
//				sendPay();
				payCheck();
			}

			@Override
			public void onFinish() {
				if(equiment==1) {
					light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
				}
			}
		});
	}
	public void sendPay(){
		Message msg = new Message();
		msg.what = 1;
		mHandler.sendMessage(msg);
	}

	private void payCheck(){
		deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
		isPay = true;
		l = 1;
		while (isPay) {
			if(isPay&&l>10){
				isPay = false;
				mHandler.sendEmptyMessage(2);
				runScanner();
			}
			if (equiment == 1) {
				isPay = false;
				mHandler.sendEmptyMessage(2);
				Message msg = new Message();
				msg.what = 1;
				mHandler.sendMessage(msg);
			}
			if (equiment != 1&&l>10)  {
				isPay = false;
				mHandler.sendEmptyMessage(2);
				runScanner();
				ToastUtil.showToast(mContext, "正在运行", ToastUtil.SUCCESS);
			}
		}
	}
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 1:
					pay();
					break;
				case 2:
					statesStr.setText("");
					deviceHandler.removeMessages(EQUIMENT_REFRESH);
				default:
					break;
			}
		}
	};

	private void pay(){
		isPress = true;
		mc.cancel(); // 定时器结束
		playBeepSoundAndVibrate(); // 播放音频
		PayAsyncTask task = new PayAsyncTask(); // 创建异步任务
		task.execute(paycode);
		isPress = false;
	}

	private void start(){
		mc.start();
		runScanner();
	}

	private void restart(){
		stopScanner(); //调用停止扫描器方法
		final LoadingDialog mProgress = new LoadingDialog(mContext, "正在重启扫描器...");
		mProgress.show();
		new Handler().postDelayed(new Runnable(){
			public void run() {
				mc.start();
				runScanner();
				mProgress.dismiss();
			}
		}, 5000);
	}

	/**
	 * 返回上一个页面
	 */
//	private void returnBack(int resultCode, String scanCode) {
//		Intent resultIntent = new Intent();
//		resultIntent.putExtra(Constant.PARAM_SCANCODE, scanCode);
//		FeixiScanActivity.this.setResult(resultCode, resultIntent);
//		finish();
//	}

	/*
	 * 展示支付金额
	 */
	private Spanned getAmountText() {
		Intent intent = getIntent();
		String amountString = intent.getStringExtra(Constant.PARAM_AMOUNT);
		String amount = "支付金额：" + amountString + "元";
		return Html.fromHtml(amount);
	}
	
	private MediaPlayer mediaPlayer;
	// 音量大小
	private static final float BEEP_VOLUME = 10.0f;
	// 震动时长
	private static final long VIBRATE_DURATION = 200L;
	// 是否震动
	private boolean vibrate = true;
	private boolean playBeep = true;

	/*
	 * 初始化音频
	 */
	private void initBeepSound() {
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		if (mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 使用系统铃声
			// mediaPlayer = MediaPlayer.create(this,
			// RingtoneManager.getActualDefaultRingtoneUri(this,
			// RingtoneManager.TYPE_NOTIFICATION));
			mediaPlayer.setOnCompletionListener(beepListener);
			mediaPlayer.setOnErrorListener(erroListener);
			AssetFileDescriptor file = getResources().openRawResourceFd(
					R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(),
						file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				// //使用系统铃声，不再调用prepare（）方法
				mediaPlayer.prepare();
			} catch (Exception e) {
				mediaPlayer = null;
			}
		}
	}

	/*
	 * 播放音频
	 */
	private void playBeepSoundAndVibrate() {
		if(mediaPlayer==null){
			initBeepSound();
		}
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}


	private static final int MESSAGE_REFRESH = 101;
	private static final int EQUIMENT_REFRESH = 102;
	private static final long REFRESH_TIMEOUT_MILLIS = 5000;
	private static final long EQUIMENT_TIMEOUT_MILLIS = 1000;
	private int l = 0;
	private final Handler deviceHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case MESSAGE_REFRESH:
					refreshDeviceList(view);
					deviceHandler.sendEmptyMessageDelayed(MESSAGE_REFRESH, REFRESH_TIMEOUT_MILLIS);
					break;
				case EQUIMENT_REFRESH:
					readDataFromPlc(redAddr);
					deviceHandler.sendEmptyMessageDelayed(EQUIMENT_REFRESH, EQUIMENT_TIMEOUT_MILLIS);
					break;
				default:
					super.handleMessage(msg);
					break;
			}
		}

	};
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if(hasFocus&&initFocus) {
			openDeviceList();
		}
	}

	private void openDeviceList(){
		ViewGroup vg = (ViewGroup)this.getWindow().getDecorView();
		view = LayoutInflater.from(mContext).inflate(R.layout.usbserial_list_activity, null);
		deviceHandler.sendEmptyMessage(MESSAGE_REFRESH);
		final ListView dlg_list = (ListView) view.findViewById(R.id.deviceList);
		mAdapter = new ArrayAdapter<UsbSerialPort>(this,
				android.R.layout.simple_expandable_list_item_2, mEntries) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final TwoLineListItem row;
				if (convertView == null){
					final LayoutInflater inflater =
							(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					row = (TwoLineListItem) inflater.inflate(android.R.layout.simple_list_item_2, null);
				} else {
					row = (TwoLineListItem) convertView;
				}

				final UsbSerialPort port = mEntries.get(position);
				final UsbSerialDriver driver = port.getDriver();
				final UsbDevice device = driver.getDevice();

				final String title = String.format("Vendor %s Product %s",
						device.getVendorId(),
						(short) device.getProductId());
				row.getText1().setText(title);

				final String subtitle = driver.getClass().getSimpleName();
				row.getText2().setText(subtitle);

				return row;
			}
		};
		dlg_list.setAdapter(mAdapter);
		dlg_list.setOnItemClickListener(new ListView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				log.info("选择：Pressed item " + position);
				if (position >= mEntries.size()) {
					log.info("提示：Illegal position.");
					return;
				}
				boolean ret = USBManager.getInstance(mContext).openUsbPort(mEntries.get(0));
				if(ret) {
					log.info("打开成功");
					Toast.makeText(mContext, "打开成功", Toast.LENGTH_SHORT).show();
					popupWindow.dismiss();
//					deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
				}else {
					log.info("打开失败");
					Toast.makeText(mContext, "打开失败", Toast.LENGTH_SHORT).show();
				}
			}
		});
//		if(popupWindow == null){
			popupWindow = new PopupWindow(vg, ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			//设置窗体的内容
			popupWindow.setContentView(view);
			popupWindow.setOutsideTouchable(true);
			popupWindow.setFocusable(true);
			popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
//		}
		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			public void onDismiss() {
				deviceHandler.removeMessages(MESSAGE_REFRESH);
				initFocus = false;
				setBackgroundAlpha(1.0f);
			}
		});
		setBackgroundAlpha(0.5f);
		popupWindow.showAtLocation(vg, Gravity.CENTER, 0, 10);
//		popupWindow.showAsDropDown(vg);
	}

	public void setBackgroundAlpha(float bgAlpha) {
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.alpha = bgAlpha;
		getWindow().setAttributes(lp);
	}

	private void refreshDeviceList(View v) {
		final ProgressBar mProgressBar = (ProgressBar)v.findViewById(R.id.progressBar);
		mProgressBar.setVisibility(View.VISIBLE);

		new AsyncTask<Void, Void, List<UsbSerialPort>>() {
			@Override
			protected List<UsbSerialPort> doInBackground(Void... params) {
				log.info("刷新设备列表");
				SystemClock.sleep(1000);
				return USBManager.getInstance(mContext).listUsbPort();
			}

			@Override
			protected void onPostExecute(List<UsbSerialPort> result) {
				mEntries.clear();
				mEntries.addAll(result);
				mAdapter.notifyDataSetChanged();
				mProgressBar.setVisibility(View.INVISIBLE);
				log.info("查找结束:Done refreshing, " + mEntries.size() + " entries found.");
			}
		}.execute((Void) null);
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
			releaseMedia();
		}
	};

	private final OnErrorListener erroListener = new OnErrorListener() {
		@Override
		public boolean onError(MediaPlayer mp, int what, int extra) {
			releaseMedia();
			return false;
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		if("1".equals(mApplication.isMT())){
			initModule();
			runScanner();
		}
		initBeepSound();
//		Log.d("ScanCode", "显示界面");
	}

	@Override
	protected void onPause() {
		super.onPause();
		if("1".equals(mApplication.isMT())){
			stopModule();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if("1".equals(mApplication.isMT())) {
			light.turnOffLight(new LightType[]{LightType.GREEN_LIGHT});
		}
	}

	private void initBankCard(){
		cardReader = (CardReader) mApplication.getDeviceInstance()
				.getStandardModule(ModuleType.COMMON_CARDREADER);
		if(cardReader==null){

		}
		EventHolder<OpenCardReaderEvent> listener = new EventHolder<OpenCardReaderEvent>();
		ModuleType[] mts = new ModuleType[]{
				ModuleType.COMMON_SWIPER,ModuleType.COMMON_ICCARDREADER };
		RFCardType[] rts = new RFCardType[]{RFCardType.ACARD};
		cardReader.openCardReader("请使用银行卡",mts,rts,true,true,30, TimeUnit.SECONDS, listener);
	}

	private class EventHolder<T extends DeviceEvent> implements DeviceEventListener<T> {
		private T event;
		private final Object syncObj = new Object();
		private boolean isClosed = false;

		public void onEvent(T event, Handler handler) {
			this.event = event;
			synchronized (syncObj) {
				isClosed = true;
				syncObj.notify();
			}
		}

		public Handler getUIHandler() {
			return null;
		}

		void startWait() throws InterruptedException {
			synchronized (syncObj) {
				if (!isClosed)
					syncObj.wait();
			}
		}

//		Swiper swiper = (Swiper) mApplication.getDeviceInstance().getStandardModule(ModuleType.COMMON_SWIPER);
//		SwiperReadModel[] srm = new SwiperReadModel[]
//		{SwiperReadModel.READ_FIRST_TRACK,SwiperReadModel.READ_SECOND_TRACK,SwiperReadModel.READ_THIRD_TRACK };
//		//步骤 1：获取刷卡结果
//		SwipResult swipRslt = swiper.readEncryptResult(srm, new WorkingKey(3) , MESeriesConst.TrackEncryptAlgorithm.BY_UNIONPAY_MODEL);
//		//步骤 2：判断刷卡是否成功
//		if (swipRslt.getRsltType() == SwipResultType.SUCCESS) {
//		//步骤 3：获取磁道信息
//			byte[] firstTrack = swipResult.getFirstTrackData(); //获取 1 磁道信息
//			byte[] secondTrack = swipResult.getSecondTrackData(); //获取 2 磁道信息
//			byte[] thirdTrack = swipResult.getThirdTrackData(); //获取 3 磁道信息
//		}
	}
	/**
	 * 停止扫描器
	 */
	private void stopScanner() {
		scanner.stopScan();
	}

	/*
	 * 释放硬件资源
	 */
	private void stopModule() {
		if (scanner != null) {
			stopScanner();
//			Log.e("TAG", "调用stopScanner方法");
		}
	}
	
	/*sc
	 * 释放音频资源
	 */
	private void releaseMedia() {
		if (mediaPlayer != null) {
			mediaPlayer.release();
			mediaPlayer = null;
//			Log.e("TAG", "释放音频资源");
		}
	}


	// 支付宝或微信支付异步任务
	public class PayAsyncTask extends AsyncTask<String, Void, String> {

		private ObjectGenerator generator = new ObjectGenerator(mContext);

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgress.show();
		}

		@Override
		protected String doInBackground(String... params) {
			String jsonStr = "";
			String rs = "";
			try {
				jsonStr = generator.getScanPayReqStr(Constant.PAY_TYPE_FEIXIPAY,0, mApplication.getOperator(), params);
				rs = WebserviceRequset.requsetService(jsonStr,mApplication.getServiceAddress());
			} catch (Exception e) {
				e.printStackTrace();
				log.error("网络请求异常："+jsonStr,e);
			}
			return rs;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mProgress.dismiss();
			//如果支付成功，关闭扫描页面
			JSONObject resultJSON = null;
			Message message = new Message();
			try {
				if("anyType{}".equals(result)){
					message.obj = "返回值anyType{}:获取不到服务器证书文件";
					message.what = Constant.BUSINESS_ERROR;
				}else{
					resultJSON = new JSONObject(result);
					String resultCode = resultJSON.getString("result");
					String returnMsg = resultJSON.getString("return_msg");
					message.obj = returnMsg;
					if(resultCode.equals("SUCCESS")) {
						message.what = Constant.BUSINESS_SUCCESS;
					}else if(resultCode.equals("FAIL")) {
						message.what = Constant.BUSINESS_FAILED;
					}else if(resultCode.equals("WAIT")) {
						message.what = Constant.BUSINESS_WAIT;
					}else {
						message.what = Constant.BUSINESS_ERROR;
					}
					light.turnOnLight(new LightType[]{LightType.GREEN_LIGHT});
				}
			} catch (JSONException e) {
				e.printStackTrace();
				log.error("网络请求异常："+result,e);
				message.obj = "数据解析错误";
				message.what = Constant.BUSINESS_ERROR;
			} finally {
				mPayHandler.sendMessage(message);
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler mPayHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case Constant.BUSINESS_SUCCESS :
					//支付成功，查询是否洗车，打开机器
					log.info("支付成功,打开设备-414");
					sendCmdToPlc(414);
					ix = 5;
					checkRestart(5);
					ToastUtil.showToast(mContext, "支付成功", ToastUtil.SUCCESS);
					break;
				case Constant.BUSINESS_FAILED : // 支付失败
				case Constant.BUSINESS_ERROR : // 支付失败
				case Constant.BUSINESS_WAIT : // 支付失败
					log.error("支付异常："+msg);
					ToastUtil.showToast(mContext, msg.obj.toString(), ToastUtil.FAIL);
					break;
				default:
					break;
			}
			start();
		}
	};

	public void checkRestart(final int sec){
		new Thread(new Runnable() {
			@Override
			public void run() {
				deviceHandler.sendEmptyMessage(EQUIMENT_REFRESH);
				l = 1;
				isRestart = true;
				MyUtils.showToast(activity, "检测启动状态");
				while (isRestart) {
					if (equiment == 1) {        //启动成功，退出
						isRestart = false;
						mHandler.sendEmptyMessage(2);
					}
					if (isRestart && l > sec) {
						isRestart = false;
						mHandler.sendEmptyMessage(2);
					}
				}
				ix--;
				if (equiment != 1 && ix > 0) {    //待机，启动不成功，重试
					log.info("重试启动");
					MyUtils.showToast(activity, "重试启动");
					activity.runOnUiThread(new Runnable() {
						  @Override
						  public void run() {
							  sendCmdToPlc(414);
						  }
					  });
					checkRestart(sec);
				}
				else if (equiment != 1 && ix < 1) {    //多次重试，仍不成功,重启设备
					log.info("重启设备");
					MyUtils.showToast(activity, "重启设备");
					activity.runOnUiThread(new Runnable() {
					   @Override
					   public void run() {
						   sendCmdToPlc(416);
					   }
				   });
				}
			}
		}).start();
	}

	public void sendCmdToPlc(int key){
		String adr = SerialUtils.readAddr(key);
		String data = SerialUtils.readData(1);
		byte[] ret = ModbusTransfer.getInstance(mContext).sendCmdToPlc(
				Integer.parseInt("1"),
				StringUtil.hexStr2Bytes(adr),
				StringUtil.hexStr2Bytes(data));
		String result = ret==null? "指令发送失败！" : "指令发送成功："+ StringUtil.byte2HexStr(ret);
//		if(ret==null){
//			sendCmdToPlc(416);
//			log.info("发送指令失败，重新启动-416");
//			//发送短信
//		}
		Toast.makeText(mContext,result+ "\n",Toast.LENGTH_LONG).show();
	}

	public void readDataFromPlc(final String addr){
		final byte[] ret = ModbusTransfer.getInstance(mContext).readDataFromPlc(
				Integer.parseInt("1"),
				StringUtil.hexStr2Bytes(addr.trim()),
				Integer.parseInt("1"),
				1000);
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				l = l +1;
				if(l>99){
					l = 0;
				}
				if(ret != null) {
					String rs = StringUtil.byte2HexStr(ret);
					equiment = Integer.valueOf(rs);
					if(equiment==1&&addr.equals("4")){
						statesStr.setText(addr+":待机中 "+l);
					}else{
						statesStr.setText(addr+":正在运行 "+l);
						equiment = 2;
					}
//					Toast.makeText(mContext, StringUtil.byte2HexStr(ret), Toast.LENGTH_SHORT).show();
				}else{
					statesStr.setText(addr+":读取数据失败 "+l);
					equiment = 0;
//					Toast.makeText(mContext,"读取数据失败！\n", Toast.LENGTH_SHORT).show();
				}
			}
		});
	}


	class MyCountDownTimer extends CountDownTimer { 
	    /** 
	     * @param millisInFuture 
	     *      表示以毫秒为单位 倒计时的总数 
	     *      例如 millisInFuture=1000 表示1秒 
	     * @param countDownInterval 
	     *      表示 间隔 多少微秒 调用一次 onTick 方法 
	     *      例如: countDownInterval =1000 ; 表示每1000毫秒调用一次onTick() 
	     */
	    public MyCountDownTimer(long millisInFuture, long countDownInterval) { 
	      super(millisInFuture, countDownInterval); 
	    } 
	  
	    @Override
	    public void onFinish() {
	    	if(!isPress){
				restart();
			}
	    } 
	  
	    @Override
	    public void onTick(long millisUntilFinished) { 
	    	mTvDownTimer.setText(String.format("%d", millisUntilFinished / 1000)); 
	    } 
	  }

}
